package com.haixiaoke.saas.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.cleaner.domain.Cleaner;
import com.haixiaoke.saas.cleaner.service.ICleanerService;
import com.haixiaoke.saas.common.annotation.DataScope;
import com.haixiaoke.saas.common.constant.TenantConstants;
import com.haixiaoke.saas.common.constant.UserConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.common.utils.StringUtils;
import com.haixiaoke.saas.common.utils.bean.BeanValidators;
import com.haixiaoke.saas.common.utils.ip.IpUtils;
import com.haixiaoke.saas.common.utils.spring.SpringUtils;
import com.haixiaoke.saas.dept.domain.BizDept;
import com.haixiaoke.saas.dept.service.IBizDeptService;
import com.haixiaoke.saas.system.domain.LoginBody;
import com.haixiaoke.saas.system.domain.LoginUser;
import com.haixiaoke.saas.system.framework.security.util.SecurityUtils;
import com.haixiaoke.saas.system.framework.web.service.UserDetailsServiceImpl;
import com.haixiaoke.saas.system.service.ISysConfigService;
import com.haixiaoke.saas.user.domain.*;
import com.haixiaoke.saas.user.mapper.BizUserBusinessMapper;
import com.haixiaoke.saas.user.service.IBizTenantUserService;
import com.haixiaoke.saas.user.service.IBizUserBusinessService;
import com.haixiaoke.saas.user.service.IBizUserDeptService;
import com.haixiaoke.saas.user.service.IBizUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.util.List;

/**
 * B端用户表Service业务层处理
 *
 * @author panda
 * @date 2023-11-14
 */
@Slf4j
@Service
public class BizUserBusinessServiceImpl implements IBizUserBusinessService {
    @Autowired
    private BizUserBusinessMapper bizUserBusinessMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IBizDeptService iBizDeptService;
    @Autowired
    protected Validator validator;
    @Autowired
    private IBizTenantUserService iBizTenantUserService;
    @Autowired
    private IBizUserRoleService iBizUserRoleService;
    @Autowired
    private IBizUserDeptService bizUserDeptService;
    @Autowired
    private ICleanerService cleanerService;
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    /**
     * 查询B端用户表
     *
     * @param userId B端用户表主键
     * @return B端用户表
     */
    @Override
    public BizUserBusiness selectBizUserBusinessByUserId(Long userId, String tenantId) {
        return bizUserBusinessMapper.selectBizUserBusinessByUserId(userId, tenantId);
    }

    /**
     * 查询B端用户表列表
     *
     * @param bizUserBusiness B端用户表
     * @return B端用户表
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<BizUserBusiness> selectBizUserBusinessList(BizUserBusiness bizUserBusiness) {
        return bizUserBusinessMapper.selectBizUserBusinessListAndDept(bizUserBusiness);
    }

    /**
     * 新增B端用户表
     *
     * @param bizUserBusiness B端用户表
     * @return 结果
     */
    @Override
    @Transactional
    public int insertBizUserBusiness(BizUserBusiness bizUserBusiness) {
        BizUserBusiness userBusiness = bizUserBusinessMapper.selectBizUserByPhonenumber(bizUserBusiness.getPhonenumber());
        if (ObjectUtil.isEmpty(userBusiness)) {
            bizUserBusiness.setCreateTime(DateUtils.getNowDate());
            bizUserBusinessMapper.insertBizUserBusiness(bizUserBusiness);
        } else {
            if (iBizTenantUserService.selectBizDepartmentUserByUserIdAndDepId(bizUserBusiness.getUserId(),bizUserBusiness.getTenantId()) >0) {
                throw new ServiceException("该用户已存在于该机构！");
            }
            bizUserBusiness.setUserId(userBusiness.getUserId());
        }
        // 新增用户与角色管理
        insertUserRole(bizUserBusiness);
        //新增用户与机构的关联
        insertDepartmentUser(bizUserBusiness);
        //新增用户与部门的关联
        insertUserDept(bizUserBusiness);
        return 1;
    }

   /* public void insertUserPost(BizUserBusiness user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }*/

    public void insertUserRole(BizUserBusiness user) {
        Long roleId = user.getRoleId();
        if (StringUtils.isNotNull(roleId)) {
            // 新增用户与角色管理
            BizUserRole ur = new BizUserRole();
            ur.setUserId(user.getUserId());
            ur.setRoleId(roleId);
            ur.setTenantId(user.getTenantId());
            iBizUserRoleService.insertBizUserRole(ur);
        }
    }


    private void insertDepartmentUser(BizUserBusiness user) {
        if (StringUtils.isNotBlank(user.getTenantId())) {
            BizTenantUser departmentUser = new BizTenantUser();
            departmentUser.setUserId(user.getUserId());
            departmentUser.setTenantId(user.getTenantId());
            departmentUser.setCreateTime(DateUtils.getNowDate());
            iBizTenantUserService.insertBizDepartmentUser(departmentUser);
        }
    }

    private void insertUserDept(BizUserBusiness user) {
        if (StringUtils.isNotNull(user.getDeptId())) {
            BizUserDept userDept = new BizUserDept();
            userDept.setUserId(user.getUserId());
            userDept.setDeptId(user.getDeptId());
            userDept.setTenantId(user.getTenantId());
            bizUserDeptService.insertUserDept(userDept);
        }
    }

    /**
     * 修改B端用户表
     *
     * @param bizUserBusiness B端用户表
     * @return 结果
     */
    @Override
    @Transactional
    public int updateBizUserBusiness(BizUserBusiness bizUserBusiness) {
        // 删除用户与角色关联
        iBizUserRoleService.deleteBizUserRoleByUserIdAndTenantId(bizUserBusiness.getUserId(), bizUserBusiness.getOldTenantId());
        // 新增用户与角色管理
        insertUserRole(bizUserBusiness);

        if (StringUtils.isNotBlank(bizUserBusiness.getTenantId())) {
            //删除用户与机构关联
            iBizTenantUserService.deleteBizDepUserByUserIdAndDepId(bizUserBusiness.getUserId(), bizUserBusiness.getOldTenantId());
            insertDepartmentUser(bizUserBusiness);
        }

        if (StringUtils.isNotNull(bizUserBusiness.getDeptId()) && StringUtils.isNotBlank(bizUserBusiness.getTenantId())) {
            // 删除用户与部门关联
            bizUserDeptService.deleteUserDeptByUserIdAndTenantId(bizUserBusiness.getUserId(), bizUserBusiness.getOldTenantId());
            insertUserDept(bizUserBusiness);
        }

        // 修改保洁人员信息
        if (bizUserBusiness.getRoleId().equals(TenantConstants.CLEANER_ROLE_ID)) {
            Cleaner cleaner = cleanerService.selectCleanerByCleanerUserId(bizUserBusiness.getUserId(), bizUserBusiness.getTenantId());
            if (ObjectUtil.isNotEmpty(cleaner)) {
                cleaner.setCleanerName(bizUserBusiness.getUserName());
                cleanerService.updateCleaner(cleaner);
            }
        }

        bizUserBusiness.setUpdateTime(DateUtils.getNowDate());
        return bizUserBusinessMapper.updateBizUserBusiness(bizUserBusiness);
    }

    /**
     * 批量删除B端用户表
     *
     * @param userIds 需要删除的B端用户表主键
     * @return 结果
     */
    @Override
    public int deleteBizUserBusinessByUserIds(Long[] userIds) {
        return bizUserBusinessMapper.deleteBizUserBusinessByUserIds(userIds);
    }

    /**
     * 删除B端用户表信息
     *
     * @param depUser B端用户表主键和机构id
     * @return 结果
     */
    @Override
    public int deleteBizUserBusinessByUserId(BizTenantUser depUser) {
        // 校验是否添加成为保洁人员
        Cleaner cleaner = cleanerService.selectCleanerByCleanerUserId(depUser.getUserId(), depUser.getTenantId());
        if (ObjectUtil.isNotEmpty(cleaner)) {
            throw new ServiceException("用户已成为保洁人员，不能删除");
        }
        // 删除用户与角色关联数据
        iBizUserRoleService.deleteBizUserRoleByUserIdAndTenantId(depUser.getUserId(), depUser.getTenantId());
        //删除用户与部门关联数据
        bizUserDeptService.deleteUserDeptByUserIdAndTenantId(depUser.getUserId(), depUser.getTenantId());
        // 删除机构与用户关联数据
        return iBizTenantUserService.deleteBizDepUserByUserIdAndDepId(depUser.getUserId(), depUser.getTenantId());
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(BizUserBusiness user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        BizUserBusiness info = bizUserBusinessMapper.checkUserNameUnique(user.getUserName(),user.getTenantId());
        if (ObjectUtil.isNotEmpty(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public BizUserBusiness selectBizUserBusinessByUserName(String username) {
        return bizUserBusinessMapper.selectBizUserBusinessByUserName(username);
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkPhoneUnique(BizUserBusiness user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        BizUserBusiness info = bizUserBusinessMapper.checkPhoneUnique(user.getPhonenumber(), user.getTenantId());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkEmailUnique(BizUserBusiness user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        BizUserBusiness info = bizUserBusinessMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean checkUserByTenantId(String tenantId) {
        int result = bizUserBusinessMapper.checkUserByTenantId(tenantId);
        return result > 0;
    }

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<BizUserBusiness> selectAllocatedList(BizUserBusiness user) {
        return bizUserBusinessMapper.selectAllocatedList(user);
    }

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<BizUserBusiness> selectUnallocatedList(BizUserBusiness user) {
        return bizUserBusinessMapper.selectUnallocatedList(user);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<BizUserBusiness> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (BizUserBusiness user : userList) {
            try {
                // 验证是否存在这个用户
                BizUserBusiness u = bizUserBusinessMapper.selectBizUserBusinessByUserName(user.getUserName());
                BizDept bizDept = iBizDeptService.selectBizDeptByDeptName(user.getDeptName());
                if (ObjectUtil.isEmpty(bizDept)) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、该部门 " + user.getDeptName() + " 不存在");
                    continue;
                }
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    user.setDeptId(bizDept.getDeptId());
                    this.insertBizUserBusiness(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    user.setUpdateBy(operName);
                    user.setDeptId(bizDept.getDeptId());
                    this.updateBizUserBusiness(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public void checkUserDataScope(Long userId) {
        BizUserBusiness user = new BizUserBusiness();
        user.setUserId(userId);
        List<BizUserBusiness> users = SpringUtils.getAopProxy(this).selectBizUserBusinessList(user);
        if (StringUtils.isEmpty(users)) {
            throw new ServiceException("没有权限访问用户数据！");
        }
    }

    @Override
    public int updateBizUserPassword(BizUserBusiness user) {
        if (user.getUserId() == null) {
            throw new ServiceException("用户标识缺失");
        }
        if (StringUtils.isEmpty(user.getNewPassword()) || StringUtils.isEmpty(user.getAgainPassword())) {
            throw new ServiceException("数据缺失");
        }
        if (!user.getNewPassword().equals(user.getAgainPassword())) {
            throw new ServiceException("两个密码不一致");
        }
        user.setUpdateTime(DateUtils.getNowDate());
        user.setPassword(SecurityUtils.encryptPassword(user.getNewPassword()));
        user.setPasswordStatus(BizUserBusiness.PASSWORD_STATUS_NO_DEFAULT);
        return bizUserBusinessMapper.updateBizUserBusiness(user);
    }

    @Override
    public List<BizUserBusiness> selectUserBusListByDep(BizUserBusiness user) {
        return bizUserBusinessMapper.selectUserBusListByDep(user);
    }

    @Override
    public int updateUserBusState(BizUserBusiness bizUser) {
        return bizUserBusinessMapper.updateBizUserBusiness(bizUser);
    }

    @Override
    public List<BizUserBusiness> selectUserBusListByDepUser(BizUserBusiness user) {
        return bizUserBusinessMapper.selectUserBusListByDepUser(user);
    }

    @Override
    public BizUserBusiness selectBizUserBusinessByphonenumber(String phonenumber, String tenantId) {
        return bizUserBusinessMapper.selectBizUserBusinessByphonenumber(phonenumber, tenantId);
    }

    @Override
    public BizUserBusiness selectBizUserByPhonenumber(String phonenumber) {
        return bizUserBusinessMapper.selectBizUserByPhonenumber(phonenumber);
    }

    @Override
    public AjaxResult checkUser(String phonenumber) {
        BizUserBusiness userBusiness = this.selectBizUserByPhonenumber(phonenumber);
        AjaxResult ajax = AjaxResult.success();
        if (ObjectUtil.isEmpty(userBusiness)) {
            ajax.put("state", false);
            return ajax;
        }
        ajax.put("state", true);
        ajax.put("userName", userBusiness.getUserName());
        return ajax;
    }

    @Override
    public boolean updateUserAvatar(Long userId, String avatar) {
        return bizUserBusinessMapper.updateUserAvatar(userId, avatar);
    }

    @Override
    public LoginUser weChatSelectUserByPhone(LoginBody loginBody) {
        String phoneNumber = loginBody.getPhonenumber();
        if (StrUtil.isBlank(phoneNumber)) {
            throw new ServiceException("手机号码为空");
        }
        if (StrUtil.isBlank(loginBody.getOpenId())) {
            throw new ServiceException("微信openid为空");
        }
        // 校验用户是否存在
        LoginUser loginUser = userDetailsService.captchaLogin(phoneNumber,loginBody.getTenantId());

        BizUserBusiness bizUser = new BizUserBusiness();
        bizUser.setUserId(loginUser.getUserId());
        bizUser.setLoginIp(IpUtils.getIpAddr());
        bizUser.setLoginDate(DateUtils.getNowDate());
        bizUser.setOpenId(loginBody.getOpenId());
        bizUserBusinessMapper.updateBizUserBusiness(bizUser);
        return loginUser;

    }

    @Override
    public int updateBizUser(BizUserBusiness user) {
        return bizUserBusinessMapper.updateBizUserBusiness(user);
    }
}
